package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.model.*;
import com.zzzyh.forumsystemclient.services.*;
import com.zzzyh.forumsystemclient.services.impl.DashScopeAIService;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import com.zzzyh.forumsystemclient.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("")
@Slf4j
public class ArticleController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private ITagService tagService;
    @Autowired
    private IUserService userService;

    @Autowired
    private DashScopeAIService dashScopeAIService;
    @Autowired
    private INotificationService notificationService;


    @RequestMapping("/api/article/list")
    public AppResult<PageResult<Article>> list(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                               @RequestParam(required = false) Integer tagId,
                                               @RequestParam(required = false) Integer categoryId,
                                               @RequestParam(required = false) String  keyword,
                                               @RequestHeader("Authorization") String token) {
        int i = 0;
        if(tagId != null){
            List<Article> articles = articleService.getArticlesByTagId(tagId,pageNum, pageSize);
            Integer total = articleService.totalByTagId(tagId);
            PageResult<Article> pageResult = new PageResult<>(pageNum, pageSize,total ,articles);
            return AppResult.success(pageResult);
        }else if(categoryId != null){
            List<Article> articles = articleService.getArticlesByCategoryId(categoryId,pageNum, pageSize);
            Integer total = articleService.totalByCategoryId(categoryId);
            PageResult<Article> pageResult = new PageResult<>(pageNum, pageSize,total ,articles);
            return AppResult.success(pageResult);
        }else if(!StringUtil.isEmpty(keyword)){
            LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
            Integer userId = user.getUser().getId();
            List<Article> articles = articleService.getArticlesByKeyword(keyword,pageNum, pageSize, userId);
            Integer total = articleService.totalByKeyword(keyword);
            PageResult<Article> pageResult = new PageResult<>(pageNum, pageSize,total ,articles);
            return AppResult.success(pageResult);
        }
        else {
            List<Article> articles = articleService.list(pageNum, pageSize);
            Integer total = articleService.total();
            PageResult<Article> pageResult = new PageResult<>(pageNum, pageSize,total ,articles);
            return AppResult.success(pageResult);
        }
    }

    @RequestMapping("/api/article/getCarousels")
    public AppResult<List<Article>> getCarousels() {
        log.info("getCarousels");
        List<Article> articles = articleService.getCarousels();
        log.info("getCarousels:{}",articles);
        return AppResult.success(articles);
    }

    @RequestMapping("/api/article/categorie-all")
    public AppResult<List<Category>> categorieAll() {
        List<Category> categories = categoryService.categorieAll();
        return AppResult.success(categories);
    }

    @RequestMapping("/api/article/getRecommends")
    public AppResult<List<Article>> getRecommends() {
        List<Article> articles = articleService.getRecommends();
        return AppResult.success(articles);
    }

    @GetMapping("/api/article/detail/{articleId}")
    public AppResult<Article> detail(@PathVariable Long articleId,
                                                   @RequestHeader("Authorization") String token) {
        Article article = articleService.getByArticleId(articleId);
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        article.setIsLike(articleService.isLike(articleId,userId ));
        article.setLikeNum(articleService.getArticleLikeTotal(articleId));
        article.setCommentNum(commentService.total(articleId));
        article.setQuantity(article.getQuantity()+1);
        article.setIsFollowAuthor(userService.isFollowAuthor(userId, article.getUserId()));
        articleService.addArticleQuantity(article.getId());
        return AppResult.success(article);
    }

    @RequestMapping("/api/article/archive")
    public AppResult<List<ArchiveResponse>> archive(){
        List<ArchiveResponse> archives = articleService.getArchivedArticles();
        return AppResult.success(archives);
    }

    @RequestMapping("/api/article/categories")
    public AppResult<List<CategoryPostResponse>> categories() {
        List<CategoryPostResponse> categoryPostResponses = articleService.getCategoryWithArticles();
        return AppResult.success(categoryPostResponses);
    }

    @RequestMapping("/api/article/myArticle")
    public AppResult<PageResult<Article>> myArticle(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                                   @RequestParam(required = false) String title,
                                                   @RequestHeader("Authorization") String token) {
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        if(!StringUtil.isEmpty(title)){
            List<Article> articles = articleService.getArticlesByTitle(title,userId, pageNum, pageSize);
            Integer total = articleService.totalByTitle(title,userId);
            PageResult<Article> pageResult = new PageResult<>(pageNum, pageSize,total ,articles);
            return AppResult.success(pageResult);
        }else {
            List<Article> articlesByUserId = articleService.getArticlesByUserId(userId, pageNum, pageSize);
            Integer total = articleService.totalByUserId(userId);
            PageResult<Article> pageResult = new PageResult<>(pageNum, pageSize,total ,articlesByUserId);
            return AppResult.success(pageResult);
        }
    }

    @RequestMapping("/api/article/like/{articleId}")
    public AppResult<Boolean> like(@PathVariable("articleId") Long articleId,
                                  @RequestHeader("Authorization") String token){
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        Integer userId = user.getUser().getId();
        if (articleService.isLike(articleId, userId) != 0){
            articleService.unlike(articleId, userId);
        }else{
            articleService.like(articleId, userId);
            Article byArticleId = articleService.getByArticleId(articleId);
            Notifications notifications = new Notifications();
            notifications.setUserId(Long.valueOf(byArticleId.getUserId()));
            notifications.setFromUserId(Long.valueOf(userId));
            notifications.setType("like");
            notifications.setTitle("点赞");
            notifications.setArticleId(articleId);
            notifications.setIsRead(false);
            notifications.setMessage(byArticleId.getTitle());
            notifications.setCreateTime(new Date());
            notificationService.add(notifications);
        }
        return AppResult.success(true);
    }

    @RequestMapping("/sys/article/add")
    public AppResult<String> add(@RequestBody Article article,
                                 @RequestHeader("Authorization") String token){
        LoginUser user = JSON.parseObject(JwtUtils.getSubjectFromToken(token), LoginUser.class);
        article.setUserId(user.getUser().getId());
//        log.info("article:{}",article);
        article.setReadType(1);
        article.setStatus(1);
        article.setQuantity(0L);
        article.setIsStick(0);

        // 如果没有提供aiDescribe且有文章内容，则使用阿里云百炼AI生成摘要
        if ((article.getAiDescribe() == null || article.getAiDescribe().trim().isEmpty())
                && article.getContent() != null && !article.getContent().trim().isEmpty()) {

            try {
                // 构建用于生成摘要的完整内容（包括简介和正文）
                StringBuilder contentForAI = new StringBuilder();
                if (article.getSummary() != null && !article.getSummary().trim().isEmpty()) {
                    contentForAI.append("文章简介：").append(article.getSummary()).append("\n\n");
                }
                contentForAI.append("文章内容：").append(article.getContent());

                // 调用阿里云百炼平台生成摘要
                String aiDescribe = dashScopeAIService.generateSummary(contentForAI.toString());
                if (aiDescribe != null && !aiDescribe.trim().isEmpty()) {
                    article.setAiDescribe(aiDescribe.trim());
                }
                log.info("AI生成的摘要: {}", aiDescribe);
            } catch (Exception e) {
                // 捕获所有异常，确保AI服务出错不影响文章发布主流程
                log.error("调用阿里云百炼AI服务生成摘要失败: {}", e.getMessage());
                // 不中断主流程，继续执行文章添加操作
            }
        }


        articleService.add(article);
        article.getTagIds().forEach(tagId -> tagService.add(tagId, article.getId()));
        return AppResult.success("添加成功");
    }

    @RequestMapping("/sys/article/update")
    public AppResult<String> update(@RequestBody Article article,
                                 @RequestHeader("Authorization") String token){
        log.info("article:{}",article);
        if (article.getContent() != null && !article.getContent().trim().isEmpty()) {

            try {
                // 构建用于生成摘要的完整内容（包括简介和正文）
                StringBuilder contentForAI = new StringBuilder();
                if (article.getSummary() != null && !article.getSummary().trim().isEmpty()) {
                    contentForAI.append("文章简介：").append(article.getSummary()).append("\n\n");
                }
                contentForAI.append("文章内容：").append(article.getContent());

                // 调用阿里云百炼平台生成摘要
                String aiDescribe = dashScopeAIService.generateSummary(contentForAI.toString());
                if (aiDescribe != null && !aiDescribe.trim().isEmpty()) {
                    article.setAiDescribe(aiDescribe.trim());
                }
                log.info("AI生成的摘要: {}", aiDescribe);
            } catch (Exception e) {
                // 捕获所有异常，确保AI服务出错不影响文章发布主流程
                log.error("调用阿里云百炼AI服务生成摘要失败: {}", e.getMessage());
                // 不中断主流程，继续执行文章添加操作
            }
        }
        articleService.update(article);
        return  AppResult.success("修改成功");
    }

    @RequestMapping("/sys/article/delete/{articleId}")
    public AppResult<String> delete(@PathVariable("articleId") Long articleId){
        articleService.delete(articleId);
        return AppResult.success("删除成功");
    }

}
